package cs543.library.rmi;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;

import org.json.JSONArray;
import org.json.JSONObject;


public class RmiClientInterface {
	private final int PORT = 12345;
	private final int TIMEOUT = 10000; // in ms
	String address = null;

	public RmiClientInterface (String address) {
		this.address = address;
	}

	protected JSONArray invoque (String iface, String method, JSONArray args) {
		JSONObject rep = null;
		try {
			Socket clientSocket = new Socket ();
			clientSocket.connect (new InetSocketAddress (address, PORT), TIMEOUT);
			DataOutputStream output = new DataOutputStream (clientSocket.getOutputStream ());
			BufferedReader input = new BufferedReader (
					new InputStreamReader (clientSocket.getInputStream()));
			
			JSONObject obj = new JSONObject ();
			obj.put ("interface", iface);
			obj.put ("method", method);
			obj.put ("args", args);
			output.writeBytes (obj.toString () + "\n");
			
			rep = new JSONObject (input.readLine ());
		} catch (Exception e) {};
		
		try {
			if (!rep.getString ("method").equals (method) || !rep.getString ("interface").equals (iface))
				return null;
			
			return rep.getJSONArray ("values");
		} catch (Exception e) {
			//try {
			//	JSONArray error = rep.getJSONArray ("errors");
			//} catch (Exception ex) {}
			return null;
		}
	}

}
